#include <iostream>
#include <vector>
#include <mutex>
#include <thread>

// 使用单例模式实现定长内存池
// template<typename T>
// class ObjectPool
//{};

template <class T>
class ObjectPool
{
public:
    T *New()
    {
        if (_free_list)
        {
            T *next = *(static_cast<T **>(_free_list));
            T *curr = static_cast<T *>(_free_list);
            _free_list = next;
            return curr;
        }
        else
        {
            //// 如果空间用完了呢？
            if (_remainder < sizeof(T))
            {
                _memory = static_cast<char *>(malloc(8 * 1024));
                if (_memory == nullptr)
                {
                    throw std::bad_alloc();
                }
                _remainder = 8 * 1024;
                _used = 0;
            }
            _remainder -= sizeof(T);
            _used += sizeof(T);
        }

        return reinterpret_cast<T *>(_memory + _used);
    }

    void Delete(T *ptr)
    {
        // 注意：作为delete，自动调用析构函数是必须的
        ptr->~T();

        *(reinterpret_cast<void **>(ptr)) = _free_list;
        _free_list = ptr;
    }

    ObjectPool(){};
    ObjectPool(const ObjectPool &) = delete;
    ObjectPool &operator=(const ObjectPool &) = delete;

private:
    char *_memory = nullptr; // 内存指针
    size_t _used = 0;
    size_t _remainder = 0;
    void *_free_list = nullptr; // 回收内存来链表
};

class Student
{
public:
private:
    std::string _name = "张三";
    size_t _age = 20;
    std::string _sex = "男";
};

void Test()
{
	const int N = 10;
	std::vector<Student*> v1;
	// lz::ObjectPool<lz::Student>* pPool = lz::ObjectPool<lz::Student>::GetPool();
	ObjectPool<Student>* pPool = new ObjectPool<Student>;
	//for (int i = 0; i < N; i++)
	//{
	//	v1.push_back(pPool->New());
	//}
	//for (int i = 0; i < N; i++)
	//{
	//	pPool->Delete(v1[i]);
	//}

	v1.clear();
}

int main()
{
	Test();
	return 0;
}